#include "MyMQTT.h"

MyMQTT::MyMQTT(PubSubClient &PubSubClient)
{
    this->client = &PubSubClient;
    this->client->setServer(_MQTT_SERVER, _MQTT_PORT);
    setup_wifi();
}

MyMQTT::~MyMQTT()
{
}

void MyMQTT::setup_wifi()
{
    delay(10);

    Serial.println();
    Serial.print("Connecting to ");
    Serial.println(_WIFI_SSID);

    WiFi.mode(WIFI_STA);
    WiFi.begin(_WIFI_SSID, _WIFI_PASS);
    WiFi.setHostname(_WIFI_STA_NAME);

    while (WiFi.status() != WL_CONNECTED)
    {
        delay(500);
        Serial.print(".");
    }
    Serial.println("");
    Serial.println("WiFi connected");
    Serial.println("IP address: ");
    Serial.println(WiFi.localIP());
}

void MyMQTT::reconnect()
{
    // Loop until we're reconnected
    while (!client->connected())
    {
        //check wifi
        if (WiFi.status() != WL_CONNECTED)
        {
            setup_wifi();
            return;
        }
        Serial.print("Attempting MQTT connection...");

        uint64_t chipid;
        chipid = ESP.getEfuseMac(); //The chip ID is essentially its MAC address(length: 6 bytes).

        String mac = String((uint16_t)(chipid >> 32), HEX); //High 2 bytes
        mac += String((uint32_t)chipid, HEX);               //Low 4bytes.

        strcpy(this->mac, mac.c_str());

        String clientId = "ESP32-MAC-";
        clientId += mac;

        Serial.println(clientId);

        // Attempt to connect
        if (client->connect(clientId.c_str(), _MQTT_USER, _MQTT_PASS))
        {
            Serial.println("connected");
            Serial.println(this->mac);

            // Once connected, 发送一个消息
            //client->publish(MQTT_PUBLISH_TOPIC, "ESP32 link in");
            //订阅
            //client->subscribe("inTopic");
        }
        else
        {
            Serial.print("failed, rc=");
            Serial.print(client->state());
            Serial.println(" try again in 5 seconds");
            // Wait 5 seconds before retrying
            delay(5000);
        }
    }
}